<template>
    <div class="meeting">
        <!-- 表格 -->
        <el-form ref="EditTableForms" :model="tableHeaderData" :rules="rules">
            <el-table ref="editTable"
                :loading="loading"
                :maxHeight="maxHeight"
                :row-key="getRowKey"
                class="w-table"
                :class="{'w-table_moving':dragStateFlag==true?dragState.dragging:''}"
                :row-class-name="tableRowClassName"
                border 
                :stripe='stripe'
                :cell-class-name="cellClassName" 
                :header-cell-class-name="headerCellClassName"
                header-row-class-name="tableHeaderClass"
                :data="tableHeaderData.props_data" :tooltip-effect="tooltip" style="width: 100%" @selection-change="handleSelectionChange" @sort-change="sortChangeTable">
                <slot name="table_before"></slot>
                <template v-for="(item,index) in tableHeader">
                    <!-- 表头全选 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='selection'" :fixed="item.fixed" :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)" :reserve-selection="true"  :align="item.align" :key="index" :width="item.width" :type="item.type"></el-table-column>
                    <!-- 复选框 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='checkbox'" :fixed="item.fixed" :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <el-form-item :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                <el-checkbox v-model="scope.row[item.prop]" @focus="handleInit(scope.row,item.prop)" @change="handleEdit(scope.row,item.prop,scope.row[item.prop])"></el-checkbox>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <!-- 多个radio -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='radio'" :fixed="item.fixed" :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <el-form-item  :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                <el-radio-group clearable v-model="scope.row[item.prop]" @focus="handleInit(scope.row,item.prop)" @change="handleEdit(scope.row,item.prop,scope.row[item.prop])">
                                    <el-radio v-for="citem in item.typeList" :key="citem.value" :label="citem.name"></el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <!-- select -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='select'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <el-form-item  :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                <el-select clearable v-model="scope.row[item.prop]" placeholder="请选择" @focus="handleInit(scope.row,item.prop)" @change="handleEdit(scope.row,item.prop,scope.row[item.prop])">
                                    <el-option v-for="citem in item.typeList"
                                        :key="citem.value"
                                        :label="citem.type"
                                        :value="citem.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <!-- 三级联动 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='cascader'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <el-form-item  :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                <el-cascader
                                v-model="scope.row[item.prop]"
                                :options="item.typeList"
                                @focus="handleInit(scope.row,item.prop)" @change="handleEdit(scope.row,item.prop,scope.row[item.prop])"></el-cascader>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <!-- 按钮表格 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='button'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :prop="item.prop" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <!-- 新增/编辑/查询按钮 -->
                            <el-button
                            v-for="citem in item.typeList"
                            :key="citem"
                            :size="citem.size"
                            :effect="citem.effect"
                            :type="citem.type"
                            @click="handleDelete(scope.$index, scope.row)">{{citem.buttonName}}</el-button>
                        </template>
                    </el-table-column>
                    <!-- 输入框 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='input'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <el-form-item  :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                <el-input v-model="scope.row[item.prop]" @focus="handleInit(scope.row,item.prop)" @change="handleEdit(scope.row,item.prop,scope.row[item.prop])"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <!-- 自定义数据字典转换 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='dictionary'" :fixed="item.fixed" :column-key="index.toString()"
                    :render-header="(h,obj) => renderheader(h,obj,item.filterProp,item.propString,item.formatterArrayString)"
                    :formatter="typeFormatter"  :align="item.align" :key="index" :prop="item.prop" :label="item.label" :width="item.width"
                    ></el-table-column>
                    <!-- 日期 -->
                    <el-table-column show-overflow-tooltip v-if="item.type=='date'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                                <el-form-item  :prop="'props_data.'+scope.$index+'.'+item.prop" :rules="rules[item.prop]">
                                    <el-date-picker
                                        v-model="scope.row[item.prop]"
                                        type="date"
                                        placeholder="选择日期"
                                        >
                                    </el-date-picker>
                                </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column show-overflow-tooltip v-if="item.type=='buttonReduce'" :fixed="item.fixed"   :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :prop="item.prop" :label="item.label" :width="item.width">
                        <template slot-scope="scope">
                            <!-- 新增/编辑/查询按钮 -->
                            <el-button icon="el-icon-search" circle
                            @click="deteleData(scope.$index, scope.row)"></el-button>
                            <!-- <el-button
                            v-for="citem in item.typeList"
                            :key="citem"
                            :size="citem.size"
                            :effect="citem.effect"
                            :type="citem.type"
                            @click="handleDelete(scope.$index, scope.row)">{{citem.buttonName}}</el-button> -->
                        </template>
                    </el-table-column>
                    <!-- 普通列 -->
                    <el-table-column show-overflow-tooltip v-else-if="item.type==''" :fixed="item.fixed"  :column-key="index.toString()" :render-header="(h,obj) => renderheader(h,obj)"  :align="item.align" :key="index" :prop="item.prop" :label="item.label" :sortable="item.isSortable">
                    </el-table-column>
                </template>
                <slot name="table_after"></slot>
            </el-table>
        </el-form>
        <!--分页-->
        <!-- <el-pagination
            v-if="isTable"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            style="text-align: right;margin:10px 0;"
            :current-page="props_pageNo"
            :page-size="pageSize"
            :page-sizes="pageSizeOpt"
            :total="props_total"
            layout="total, sizes, prev, pager, next, jumper">
        </el-pagination> -->
        <pagingModule :props_total="props_total" :isTable="isTable" :props_pageNo="props_pageNo" :pageSize="pageSize" :pageSizeOpt="pageSizeOpt"  @pageBefore="handleBefore" :isSmall="false"></pagingModule>
    </div>
</template>
<script>
    // import qs from 'qs'
    import request from '@/utils/request.js'
    import pagingModule from "../pagingModule";
    export default {
        name: "EditTable",
        props: {
            onlyId:{
                type: String
            },
            dragStateFlag:{
                type: Boolean,
                default: false
            },
            url:String,
            apiName:Function,
            tooltip:String,//dark、
            columns: {
                type: Array,
                default: () => []
            },
            rules:{
                type: Object,
            },
            isShowChild: {
                type: Boolean,
                default: false
            },
            tableData: {
                type: Array,
                default: () => []
            },
            stripe: {
                type: Boolean,
                default: false
            },
            pageSizeOpt:{
                type: Array,
                default() {
                    return [10, 20, 30, 50, 100];
                }
            },
            pageNum: {
                type: Number,
                default: 1
            },
            pageSize: {
                type: Number,
                default: 10,
            },
            maxHeight: {
                type: Number,
                default: 2000
            },
            tableRowClassName:{
                type: Function,
            }
        },
        components:{
            pagingModule
        },
        data() {
            return {
                
                tableHeader:this.columns,
                // 拖拽列
                dragState: {
                    start: -9, // 起始元素的 index
                    end: -9, // 移动鼠标时所覆盖的元素 index
                    dragging: false, // 是否正在拖动
                    direction: undefined // 拖动方向
                },
                isTable:true,
                loading:false,
                tableHeaderData:{
                    props_data: [],
                },
                props_total: 0,
                props_pageNo: this.pageNum,
                props_query: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                },
                saveData:[],
                rowNum:1,
                checkedDetail:[],
                formatterList:{
                    "sex":[{"value":1,"type":"男"},{"type":"女","value":0}],
                    "IS_MARRY":[{isMarry:1,name:"是"},{isMarry:0,name:"否"}],
                    "STATE":[{"state":0,"type":'提交'},{"state":1,"type":'审核中'},{"state":2,"type":'已通过'},{"state":3,"type":'已拒绝'}],
                    "LEVEL":[{"level":"1","type":"一级"},{"level":"2","type":"二级"},{"level":"3","type":"三级"}]
                },
                inquireData:{},

            }
        },
        created(){
        },
        mounted(){
            if(!this.isShowChild){//布局格式
                this.query();
            }
        },
        watch: {
            isShowChild: {
                handler(newValue, oldValue) {
                    this.tableHeaderData.props_data = this.tableData
                },
                deep: true
            }
            ,
        　　 tableData: {
                handler(newValue, oldValue) {
                    this.tableHeaderData.props_data = this.tableData
                },
                deep: true
　　　　　　  },
            columns (val, oldVal) {
                this.tableHeader = val
            }   
　　　　 },
        methods: {
            getRowKey(rows){
                return rows[this.onlyId];
            },
            // 拖拽列置换
            /*******开始**********/
            renderheader(h, { column, $index },formatterObject,propString,formatterArrayString){
                column.formatterArray = formatterObject?formatterObject:this.formatterList[formatterArrayString];//
                column.propString = propString?propString:[]; //转换后字段名
                // column.filterType = filterType?filterType:""; //判断是自定义转换customDictionary还是数据字典转换dictionary
                return h('div',{
                        'class': ['thead-cell'],
                        on: {
                            mousedown: ($event) => { this.handleMouseDown($event, column) },
                            mousemove: ($event) => { this.handleMouseMove($event, column) }
                        }
                    }, [
                        // 添加 <a> 用于显示表头 label
                        h('a',{}, column.label),
                        // 添加一个空标签用于显示拖动动画
                        // createElement('span', {
                        //     'class': ['virtual']
                        // })
                    ])
            },
            // 按下鼠标开始拖动
            handleMouseDown (e, column) {
                this.dragState.dragging = true
                this.dragState.start = parseInt(column.columnKey)
                // 给拖动时的虚拟容器添加宽高
                let table = document.getElementsByClassName('w-table')[0]
                let virtual = document.getElementsByClassName('virtual')
                for (let item of virtual) {
                    item.style.height = table.clientHeight - 1 + 'px'
                    item.style.width = item.parentElement.parentElement.clientWidth + 'px'
                }　
                document.addEventListener('mouseup', this.handleMouseUp);
            },
            // 鼠标放开结束拖动
            handleMouseUp () {
                this.dragColumn(this.dragState)
                // 初始化拖动状态
                this.dragState = {
                    start: -9,
                    end: -9,
                    dragging: false,
                    direction: undefined
                }　
                document.removeEventListener('mouseup', this.handleMouseUp);
            },
            // 拖动中
            handleMouseMove (e, column) {
                if (this.dragState.dragging) {
                    let index = parseInt(column.columnKey) // 记录起始列
                    if (index - this.dragState.start !== 0) {
                        this.dragState.direction = index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
                        this.dragState.end = parseInt(column.columnKey)
                    } else {
                        this.dragState.direction = undefined
                    }
                }else{
                    return false
                }
            },
            // 拖动易位
            dragColumn ({start, end, direction}) {
                let tempData = []
                let left = direction === 'left'
                let min = left ? end : start - 1
                let max = left ? start + 1 : end
                for (let i = 0; i < this.tableHeader.length; i++) {
                    if (i === end) {
                        tempData.push(this.tableHeader[start])
                    } else if (i > min && i < max) {
                        tempData.push(this.tableHeader[ left ? i - 1 : i + 1 ])
                    } else {
                        tempData.push(this.tableHeader[i])
                    }
                }
                this.tableHeader = tempData
            },
            headerCellClassName (column, columnIndex) {
                let active = columnIndex - 1 === this.dragState.end ? `darg_active_${this.dragState.direction}` : ''
                let start = columnIndex - 1 === this.dragState.start ? `darg_start` : ''
                return `${active} ${start}`
            },
            cellClassName (column, columnIndex) {
                return (columnIndex - 1 === this.dragState.start ? `darg_start` : '')
            },
            /*******结束**********/
            //查询
            query(arg) {
                let that = this;
                that.loading = true;
                let param = Object.assign(that.props_query,arg || {});
                that.inquireData=arg || {};
                if(arg && arg.pageNum){
                    param.pageNum = arg.pageNum;
                }
                let apiName = that.apiName;
                if(!apiName){
                    that.tableHeaderData.props_data = that.tableData ? that.tableData : [];
                    that.saveData = that.tableData ? [...that.tableData] : [];
                    that.saveDataInit();
                    return;
                }
                // qs.stringify
                apiName(param).then(res => {
                    that.loading = false;
                    res = res && res.rspBody ? res.rspBody : {}
                    if(JSON.stringify(res) == '{}'){
                        // that.props_data = []
                        // that.saveData = []
                        // debugger
                        that.tableHeaderData.props_data = that.tableData//暂时 只是为了效果展示
                        that.saveData = that.tableData ? [...that.tableData] : [];//暂时 只是为了效果展示
                        that.props_pageNo = that.pageNum || 1;//暂时 只是为了效果展示
                        that.props_total = that.tableData.length;//暂时 只是为了效果展示
                        that.saveDataInit();//暂时 只是为了效果展示
                        return 
                    }
                    res.resultData = res.resultData ? res.resultData : []
                    that.tableHeaderData.props_data = res.resultData;
                    that.props_pageNo = res.pageNum || 1;
                    that.props_total = res.total ? res.total :0;
                    that.saveDataInit();
                    that.$emit('queryResult', res);
                });
            },
            handleBefore(pageArr) {
                if(pageArr.pageType=="size"){
                    this.query({
                        pageNum:1,
                        pageSize:pageArr.pageSize
                    });
                }else{
                    var changeFlag = false;
                    for(var i=0;i<this.saveData.length;i++){
                        if(this.saveData[i].opt&&this.saveData[i].opt == "insert"||this.saveData[i].opt == "update"||this.saveData[i].opt == "delete"){
                            changeFlag = true;
                            break;
                        }
                    }
                    if(changeFlag){
                        this.$alert("请先保存修改再切换分页", "提示");
                        return false;
                    }
                    this.query({
                        pageNum:pageArr.page
                    });
                }
                
            },
            deteleData(index,row){
                
            },
            // updateData(data){
            //     this.props_data = data;
            // },
            // 初始化数据
            saveDataInit() {
                for(var i=0;i<this.tableHeaderData.props_data.length;i++){
                    this.tableHeaderData.props_data[i].rowNum = this.rowNum;
                    this.rowNum++;
                }
                this.saveData = this.tableHeaderData.props_data ? [...this.tableHeaderData.props_data] : [];
            },
            // 给数据添加默认值
            handleInit(row,prop) {
                let oldValue = 'old'+prop;
                if(!row[oldValue]){
                    row[oldValue] = row[prop];
                }
            },
            // 新增行
            addRow(list) {
                if(this.tableHeaderData.props_data == undefined){
                    this.tableHeaderData.props_data = new Array();
                }
                list.opt='insert';
                list.rowNum = this.rowNum;
                this.tableHeaderData.props_data.unshift(list);
                this.saveData.unshift(list);
                this.rowNum++;
            },
            // 给更改过的数据增加状态
            handleEdit(row,prop,value) {
                let oldValue = 'old'+prop;
                if(row.opt != "insert"&&row.opt != "delete"){
                    if(row[oldValue] != value){
                        row.opt = "update";
                    }else{
                        delete row.opt;
                    }
                }
            },
            // 删除行
            deleteRow() {
                let that = this
                if (that.checkedDetail.length == 0) {
                    that.$alert("请先选择要删除的数据", "提示", {
                        confirmButtonText: "确定",
                    });
                } else {
                    for (let i = 0; i < that.checkedDetail.length; i++) {
                        let data = that.checkedDetail
                        // 获取选中行的索引的方法
                        // 遍历表格中props_data数据和选中的val数据，比较它们的rowNum,相等则输出选中行的索引
                        // rowNum的作用主要是为了让每一行有一个唯一的数据，方便比较，可以根据个人的开发需求从后台传入特定的数据
                        data.forEach((val, index) => {
                            that.tableHeaderData.props_data.forEach((v, i) => {
                                if (val.rowNum === v.rowNum) {
                                    // i 为选中的索引
                                    that.tableHeaderData.props_data.splice(i, 1);
                                }
                            })
                            that.saveData.forEach((item,index) => {
                                if(val.rowNum == item.rowNum){
                                    if(item.opt == "insert"){
                                        that.saveData.splice(index, 1);
                                    }else{
                                        item.opt = "delete";
                                    }
                                }
                            })
                            console.log('del')
                        })
                    }
                    // 删除完数据之后清除勾选框
                    that.$refs.editTable.clearSelection();
                    // console.log(this.props_data);     
                    // console.log(this.saveData);
                }
            },
            // 选中的数据
            handleSelectionChange(selection) {
                this.checkedDetail = selection;
                
                this.$emit('selectionChange', selection);
            },
            // 小代码转换
            typeFormatter(row, column){
                for (var i in column.formatterArray) {
                    if (row[column.propString] == column.formatterArray[i][column.propString]){
                        row = Object.assign(row,column.formatterArray[i]);
                    }
                }
                // console.log(row);
                return row[column.property];
            },
            //排序
            sortChangeTable(column){
                this.$emit("sortChangeTableAfter",column);
                if(column.column.sortable=="custom"){
                    var fieldName = column.prop;
                    var sortingType = column.order;
                    //按照降序排序
                    if(sortingType == "descending"){
                        // sid asc desc
                        this.query({
                            order : fieldName+ " desc"
                        });
                    }
                    //按照升序排序
                    else{
                        this.query({
                            order : fieldName+ " asc"
                        });
                    }
                }
            }
            
        }
    };
</script>
<style>
.el-table th {
    background-color:#fff !important;
    
}
.el-table--border, .el-table--group{
     border-left:1px solid #99d2ff;
}
/* table{
    border-left:1px solid #99d2ff;
} */
.el-table--border td, .el-table--border th, .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed{
    border-right: 1px solid #99d2ff;
}
.el-table td, .el-table th.is-leaf{
    border-bottom:1px solid #99d2ff;
}
.tableHeader th {
    background-color:#fff !important;
}
 /* lang="less" scoped */
 .meeting{
    width: 100%;
    margin-top:10px;
}
.el-table th{
    background-color: #f8f8f9;
    color: #515a6e;
    height: 40px; 
    font-size: 13px;
}
.el-table tr,.el-table td{
    height:48px; 
    padding: 0px;
    box-sizing:border-box;
}
/* 日期控件icon */
.el-table .el-input__icon{
    line-height:24px;
}
.el-table .el-button{
    padding:4px 15px;
}
.el-table .el-input__inner{
    height:24px;
    line-height:24px;
    font-size:12px;
}
.el-table th{
    padding:0px;
}
.el-table .el-date-editor.el-input,.el-table .el-date-editor.el-input__inner{
    width:90%;
}
/* 日期控件icon */
.el-table .el-input__icon{
    line-height:24px;
}
.el-table .el-button{
    padding:4px 15px;
} 
.w-table .el-table .darg_start { background-color: #f3f3f3; }

.w-table .el-table th { padding: 0; }

.w-table .el-table th .virtual { position: fixed; display: block; width: 0; height: 0; margin-left: -10px; background: none; border: none; }

.w-table .el-table .darg_active_left { border-left: 2px dotted #666; z-index: 99; }

.w-table .el-table .darg_active_right { border-right: 2px dotted #666; z-index: 99; }

.w-table .thead-cell { padding: 0; display: inline-flex; flex-direction: column; align-items: left; cursor: pointer; overflow: initial; }

.w-table .thead-cell:before { content: ""; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }

.w-table.w-table_moving .el-table th .cell .thead-cell { cursor: move !important;}

.w-table.w-table_moving .el-table__fixed { cursor: not-allowed; }
 .el-table .el-table__header-wrapper .el-table__header th{
    height: 40px!important;
}

.el-table .el-form-item{
    margin-bottom: 15px;
}
.el-table .el-form-item .el-form-item__error{
    padding: 0px;
}
.el-table .el-form-item__content{
    line-height: 30px;
}
</style>